//
//  FingerprintUnlockViewController.m
//  YTwallet
//
//  Created by ZhangLin on 2019/3/20.
//  Copyright © 2019年 hadrlog. All rights reserved.
//

#import "FingerprintUnlockViewController.h"
#import "FingerprintView.h"
//指纹验证
#import <LocalAuthentication/LocalAuthentication.h>

//登录页面
#import "LoginViewController.h"
#import "NavigateViewController.h"
#import "TabBarController.h"

#import "LoginModelPack.h"

@interface FingerprintUnlockViewController ()
@property(nonatomic,strong)FingerprintView *fv;

@end

@implementation FingerprintUnlockViewController

-(void)loadView
{
    [super loadView];
    self.fv = [[FingerprintView alloc] initWithFrame:self.view.bounds];
    self.view = self.fv;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self TouchIdVerify];
    NSLog(@"页面初始");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.fv.passwordLoginBtn addTarget:self action:@selector(passwordLoginBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.fv.fingerPrintBtn addTarget:self action:@selector(fingerPrintBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
}
-(void)passwordLoginBtnAction
{
    NSLog(@"点击密码登录");
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.type = LoginVCFromFingerfrintVerifyVC;
    NavigateViewController *nav = [[NavigateViewController alloc] initWithRootViewController:loginVC];
    [self presentViewController:nav animated:YES completion:nil];
}

-(void)fingerPrintBtnAction
{
    NSLog(@"点击验证指纹");
    [self TouchIdVerify];
}
-(void)fingerPrintLogin
{
    NSString *url = [[ServerAddressModel shareInstance] fullTAnd0AddrWithParameter:@"/epay_apps/login/fingerPrint"];
    [[ETONEHttpClient sharedInstance] doHTTPSPOST:url Parameters:nil HttpBody:nil SuccessHandler:^(id responseObject) {
        
        NSDictionary *dic = [responseObject mj_JSONObject];
        NSString *code = dic[@"code"];
        if ([@"0000" isEqualToString:code]) {
        [self loginSuccessWithResponse:responseObject];
        }
        
    } FailedHandler:^(NSError *error) {
        
    }];
}

//登录成功跳转
-(void)loginSuccessWithResponse:(id )responseObject
{
    
    NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    
    //解析数据
    NSDictionary *dic = [responseObject mj_JSONObject];
    LoginResponse *loginResponse = [LoginResponse mj_objectWithKeyValues:dic];
    [AppTools shareInstance].userInfo = loginResponse.response.userInfo;
    [AppTools shareInstance].msgInfo = loginResponse.response.msgInfo;
    
    /*
    //把登录返回的数据模型存储到本地
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:loginResponse.response.userInfo];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"u"];
     */
    
    //登录成功   更新在本地保存的token
    [AppTools setToken:loginResponse.response.auth_token];

    //记录登录状态
    [AppTools saveLoginStatus:YES];
    

    TabBarController *tabVC = [[TabBarController alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabVC;

}

-(void)TouchIdVerify
{
    NSString *version = [UIDevice currentDevice].systemVersion;
    if ([version integerValue] < 8.0) {
        NSLog(@"系统版本不支持TouchID");
        return;
    }
    LAContext *context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"验证密码登录";
    NSError *error = nil;
    
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
            
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"TouchID 验证成功");
                    
                    //调用登录接口
                    [self fingerPrintLogin];
                    
                    /*
                    //登录成功
                    AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
                    appDelegate.accountStatus = ETNOAutonym;
                    
                    //记录登录状态
                    [AppTools saveLoginStatus:YES];
                    
                    
                    
                    //跳转到首页去
                    TabBarController *tabBarVc = [[TabBarController alloc] init];
                    [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVc;
                     */
                });
            }else if(error){
 
                switch (error.code) {
                    case LAErrorAuthenticationFailed:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 验证失败");
                            //当第三次的时候系统会提示验证失败
                            [self showFailedResultTips:@"验证失败" animated:YES forSeconds:1.5];
                        });
                        break;
                    }
                    case LAErrorUserCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被用户手动取消");
                        });
                    }
                        break;
                    case LAErrorUserFallback:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"用户不使用TouchID,选择手动输入密码");
                            [self passwordLoginBtnAction];
                        });
                    }
                        break;
                    case LAErrorSystemCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 被系统取消 (如遇到来电,锁屏,按了Home键等)");
                        });
                    }
                        break;
                    case LAErrorPasscodeNotSet:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置密码");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotEnrolled:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无法启动,因为用户没有设置TouchID");
                        });
                    }
                        break;
                    case LAErrorTouchIDNotAvailable:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"TouchID 无效");
                        });
                    }
                        break;
                    case LAErrorTouchIDLockout:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self openSystemPassword];
                            NSLog(@"TouchID 被锁定(连续多次验证TouchID失败,系统需要用户手动输入密码)");
                        });
                    }
                        break;
                    case LAErrorAppCancel:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (如App进入了后台等)");
                        });
                    }
                        break;
                    case LAErrorInvalidContext:{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"当前软件被挂起并取消了授权 (LAContext对象无效)");
                        });
                    }
                        break;
                    default:
                        break;
                }
            }
        }];
        
    }else{
        NSLog(@"当前设备不支持TouchID");
        //打开系统密码
        [self openSystemPassword];
    }
}

-(void)openSystemPassword
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        LAContext *myContext=[[LAContext alloc] init];
        NSError *error=nil;
        
        if([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error])
        {
            [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"通过Home键验证已有手机指纹" reply:^(BOOL success, NSError * _Nullable error) {
                
            }];
            
        }
    });
}

@end
